/**
 * 是否Android系统
 * */
function isAndroid() {
    return navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1
}
/**
 * 是否为IOS系统
 * */
function isIOS() {
    return !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

/**
 * 验证手机号码
 * @param {Number} phone 手机号
 * */
function checkPhone(phone) {
    return /^1[0-9]{10}/.test(phone)
}

/**
 * 身份证号验证
 * @param {String | Number} sIdCard 身份证号
 * */
function checkIdCard(sIdCard) {
    //Wi 加权因子 Xi 余数0~10对应的校验码 Pi省份代码
    let Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2],
        Xi = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2],
        Pi = [11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51, 52, 53, 54, 61, 62, 63, 64, 65, 71, 81, 82, 91],
        checkStatus = 0
    // 检查身份证长度
    if (sIdCard.length == 18) {
        checkStatus += 1
    }
    //检验输入的省份编码是否有效
    if (checkStatus >= 1) {
        let p2 = sIdCard.substr(0, 2)
        for (let i = 0; i < Pi.length; i++) {
            if (Pi[i] == p2) {
                checkStatus += 1
            }
        }
    }
    //检验18位身份证号码出生日期是否有效
    //parseFloat过滤前导零，年份必需大于等于1900且小于等于当前年份，用Date()对象判断日期是否有效。
    if (checkStatus >= 2) {
        let year = parseFloat(sIdCard.substr(6, 4))
        let month = parseFloat(sIdCard.substr(10, 2))
        let day = parseFloat(sIdCard.substr(12, 2))
        let checkDay = new Date(year, month - 1, day)
        let nowDay = new Date()
        if (1900 <= year && year <= nowDay.getFullYear() && month == checkDay.getMonth() + 1 && day == checkDay.getDate()) {
            checkStatus += 1
        }
    }
    //检验校验码是否有效
    if (checkStatus >= 3) {
        let aIdCard = sIdCard.split('')
        let sum = 0
        for (let j = 0; j < Wi.length; j++) {
            sum += Wi[j] * aIdCard[j] //线性加权求和
        }
        let index = sum % 11 //求模，可能为0~10,可求对应的校验码是否于身份证的校验码匹配
        if (Xi[index] == aIdCard[17].toUpperCase()) {
            checkStatus += 1
        }
    }
    if (checkStatus == 4) {
        return true
    } else {
        return false
    }
}

// md5加密
function omEncrypt(str) {
    return SparkMD5.hash(str)
}

/**
 * 参数排序 =》去除空字段
 * @method objKeySort
 * @param {String} str 格式：details--id-46--user_id-1
 * @return {Object}
 * */
function objKeySort(jsonData) {
    try {
        let tempJsonObj = {}
        let sdic = Object.keys(jsonData).sort()
        sdic.map((item, index) => {
            if ((typeof jsonData[item] === 'string' && !jsonData[item]) || jsonData[item] == undefined) return
            tempJsonObj[item] = jsonData[sdic[index]]
        })
        // console.log('将返回的数据进行输出',tempJsonObj);
        return tempJsonObj
    } catch (e) {
        return jsonData
    }
}
/**
 * 格式化参数
 * @method convertFormat
 * @param {Object} query 携带的参数
 * @return {String} 格式：id=46&user_id=1
 * */
function convertFormat(query) {
    let str = ''
    if (JSON.stringify(query) !== '{}') {
        let dyadicArray = Object.entries(query)

        // 二维数组转一维数组
        let arr = dyadicArray.map((item) => item.join('='))

        str = arr.join('&')
    }
    // console.log(name, query, arr, dyadicArray)
    // console.log(str)
    return str
}

// 微信授权
function weChatAuthorize(redirect) {
    var appid = 'xxx'
    var redirect_uri = redirect
    var response_type = 'code'
    var scope = 'snsapi_userinfo'
    var state = 'state'
    // alert(redirect_uri + '/ appid:' + appid)
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}#wechat_redirect`
}
// token是否过期
function isAuthorize() {
    var token = sessionStorage.getItem('token')
    var date = Date.now() / 1000
    token = !token ? token : JSON.parse(token)
    if (!token) {
        return false
    } else {
        // console.log(token)
        if (token.expires_time > date) {
            return true
        }
        return false
    }
}

//	请求接口获取token
function getTokenAccessApi(code, cb) {
    axios
        .post(BASE_URL + 'Wechat/mp', {
            code: code,
            type: 1
        })
        .then(function (res) {
            if (res.data.code === 1) {
                var token = res.data.data
                sessionStorage.setItem('token', JSON.stringify(token))
                cb && cb()
            } else {
                console.log(res)
            }
        })
}

// 储存token
function reserveToken(self, cb) {
    // console.log(!isAuthorize())
    if (!isAuthorize()) {
        if (location.href.indexOf('code=') !== -1) {
            var code = location.href.split('code=')[1]
            if (code.indexOf('&') !== -1) {
                code = code.split('&')[0]
            }
            // console.log(code)
            getTokenAccessApi(code, cb)
            return
        }
        weChatAuthorize(location.href)
    } else {
        cb && cb()
    }
}

// 取token
function getToken() {
    var token = sessionStorage.getItem('token')
    token = !token ? token : JSON.parse(token)
    if (!token) {
        return ''
    } else {
        return token.access_token
    }
}

//上传图片
function uploadFile(_this, formData, cb) {
    axios
        .post(BASE_URL + 'Util/uploadFiles', formData, {
            onUploadProgress: (progressEvent) => {
                var complete = (((progressEvent.loaded / progressEvent.total) * 100) | 0) + '%'
                _this.progress = complete
            },
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then(function (res) {
            if (res.data.code === 1) {
                _this.messeage('上传成功')
                cb && cb(res.data.data[0])
            } else {
                console.log(res)
            }
        })
}

;(function (doc, win) {
    var useragent = navigator.userAgent
    // if (useragent.match(/MicroMessenger/i) != 'MicroMessenger') {
    // 	window.location.href = 'err.html'
    // }

    //      用原生方法获取用户设置的浏览器的字体大小(兼容ie)
    if (doc.documentElement.currentStyle) {
        var user_webset_font = doc.documentElement.currentStyle['fontSize']
    } else {
        var user_webset_font = getComputedStyle(doc.documentElement, false)['fontSize']
    }

    // 取整后与默认16px的比例系数
    var xs = parseFloat(user_webset_font) / 16
    // console.log(xs)
    //  设置rem的js设置的字体大小
    var view_jsset_font, result_font
    var docEl = doc.documentElement,
        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
        clientWidth,
        recalc = function () {
            clientWidth = docEl.clientWidth
            if (!clientWidth) return
            if (!doc.addEventListener) return
            //  设置rem的js设置的字体大小
            view_jsset_font = clientWidth / 10
            //  最终的字体大小为rem字体/系数
            result_font = view_jsset_font / xs
            //  设置根字体大小
            docEl.style.fontSize = result_font + 'px'
        }

    win.addEventListener(resizeEvt, recalc, false)

    doc.addEventListener('DOMContentLoaded', recalc, false)
})(document, window)
